8 ROS2 -Writing a simple publisher and subscriber (Python)

  • Installing MS Code
    Pasted image 20251012094559.png

Pasted image 20251012094611.png

Pasted image 20251012094620.png
Pasted image 20251012094628.png

Create a package

  • Open a terminal and run:
cs
ros2 pkg create --build-type ament_python py_pubsub
cd py_pubsub/py_pubsub/
wget https://raw.githubusercontent.com/ros2/examples/humble/rclpy/topics/minimal_publisher/examples_rclpy_minimal_publisher/publisher_member_function.py

Pasted image 20251012094800.png

Pasted image 20251012094808.png

Explaining the code

Pasted image 20251012094831.png

Add dependencies

  • Open package.xml with your text editor, add these lines:
<exec_depend>rclpy</exec_depend>
<exec_depend>std_msgs</exec_depend>
  • Open the setup.py file, add these lines.
entry_points={
        'console_scripts': [
                'talker = py_pubsub.publisher_member_function:main',
        ],
},

Write the subscriber node

In the same terminal and run:

cs
cd py_pubsub/py_pubsub/
wget https://raw.githubusercontent.com/ros2/examples/humble/rclpy/topics/minimal_subscriber/examples_rclpy_minimal_subscriber/subscriber_member_function.py

Pasted image 20251012095118.png

Explaining the code

Pasted image 20251012095139.png

  • Open the setup.py file, add these lines.
entry_points={
        'console_scripts': [
                'talker = py_pubsub.publisher_member_function:main',
                'listener = py_pubsub.subscriber_member_function:main',
        ],
},
  • In the same terminal and run:
ros2 run py_pubsub talker
  • Open another terminal and run:
ros2 run py_pubsub listener